package ddz;

import sun.misc.Signal;
import sun.misc.SignalHandler;

/**
 * 优雅退出系统
 */
public class ExitSys implements SignalHandler {

    private Runnable shutdownHook;

    <T> T init(Runnable shutdownHook) {
        Signal signal = new Signal(this.getOSSignalType());
        Signal.handle(signal, this);
        this.shutdownHook = shutdownHook;
        return (T) shutdownHook;
    }

    private String getOSSignalType() {
        return System.getProperties().getProperty("os.name").
                toLowerCase().startsWith("win") ? "INT" : "USR2";
    }

    private void invokeShutdownHook() {
        Thread t = new Thread(shutdownHook, "ShutdownHook-Thread");
        Runtime.getRuntime().addShutdownHook(t);
    }

    @Override
    public void handle(Signal signal) {
        this.invokeShutdownHook();
        Runtime.getRuntime().exit(0);
    }
}
